﻿using System;
using Microsoft.SharePoint.Workflow;
using System.Text;

namespace TPG.SharePoint.Workflow
{
  public static class WorkflowConfiguration
  {
    internal const string DataTypeText = "Text";
    internal const string DataTypeUrl = "Url";
    internal const string DataTypeSerializationMode = "SerializationMode";

    public static SerializationMode? GetSerializationMode(
      SPWorkflowTemplate template, PageType pageType)
    {
      string serializationModeString = LookupMetadata(template, pageType,
        String.Empty, String.Empty, DataTypeSerializationMode, false);
      return String.IsNullOrEmpty(serializationModeString) ?
        (SerializationMode?)null : 
        EnumUtils.SafeParseEnum<SerializationMode>(serializationModeString);
    }

    internal static string LookupMetadata(SPWorkflowTemplate template,
        PageType pageType, string placeHolderType,
        string location, string dataType,
        bool fallbackToNoPlaceHolderType)
    {
      string value = LookupMetadataInternal(
          template, pageType, placeHolderType, location, dataType, true);
      if (String.IsNullOrEmpty(value) && fallbackToNoPlaceHolderType)
      {
        value = LookupMetadataInternal(
        template, pageType, placeHolderType, location, dataType, false);
      }
      return value;
    }

    static string LookupMetadataInternal(SPWorkflowTemplate template,
        PageType pageType, string placeHolderType,
        string location, string dataType,
        bool includePlaceHolderType)
    {
      StringBuilder lookup = new StringBuilder();
      lookup.AppendFormat("{0}_", pageType.ToString());
      if (includePlaceHolderType && String.IsNullOrEmpty(placeHolderType) == false)
      {
        lookup.AppendFormat("{0}_", placeHolderType);
      }
      lookup.Append(location);
      lookup.Append(dataType);
      return (string)template[lookup.ToString()];
    }
  }
}
